﻿using System.Linq;
using System.Security.Cryptography.X509Certificates;

namespace Ipmce.RemoteVoting.Frontend.VotingApplication.Utils
{
	class CertificateProvider : ICertificateProvider
	{
		private readonly string _rootCaName;

		public CertificateProvider(string rootCaName)
		{
			_rootCaName = rootCaName;
		}

		public CertificateInfo[] GetPrivateCertificateInfos()
		{
			var storeMy = new X509Store(StoreName.My, StoreLocation.CurrentUser);
			storeMy.Open(OpenFlags.ReadOnly);
			var result = storeMy.Certificates.Find(X509FindType.FindByIssuerName, _rootCaName, true).Cast<X509Certificate2>()
				.Select(c => new CertificateInfo
			{
				DistinguishName = c.SubjectName.Name,
				Thumbprint = c.Thumbprint
			}).ToArray();
			storeMy.Close();
			return result;
		}

		public X509Certificate2 GetCertificate(string thumbPrint)
		{
			var storeMy = new X509Store(StoreName.My, StoreLocation.CurrentUser);
			storeMy.Open(OpenFlags.ReadOnly);
			var result = storeMy.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);
			storeMy.Close();
			return result[0];
		}
	}
}